package com.mcy.springbatch.job;

import com.mcy.springbatch.entity.SysUser;
import com.mcy.springbatch.job.BaseJobConfig;
import com.mcy.springbatch.listener.JobListener;
import com.mcy.springbatch.listener.StepListener;
import com.mcy.springbatch.writer.SysUserItemWriter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.batch.item.ItemWriter;
import org.springframework.batch.item.support.ListItemReader;
import org.springframework.batch.item.support.ListItemWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;

/**
 * Job和Step的监听器Demo
 */
@Slf4j
@Configuration
public class FJobAndStepLinstenerJobConfig extends BaseJobConfig {

    @Autowired
    private JobListener jobListener;

    @Autowired
    private StepListener stepListener;

    @Autowired
    private ListItemReader<SysUser> userDataListItemReader;

    @Autowired
    private SysUserItemWriter sysUserItemWriter;

    @Bean
    public Job listenerJob(){
        return jobBuilderFactory.get("listenerJob")
                .incrementer(new RunIdIncrementer())
                .start(listenerJobStep())
                .listener(jobListener)
                .build();
    }

    @Bean
    public Step listenerJobStep(){
        return stepBuilderFactory.get("listenerJobStep")
                .<SysUser,SysUser>chunk(10)
                .faultTolerant()
                .listener(stepListener)
                .reader(userDataListItemReader)
                .processor(processor())
                .writer(sysUserItemWriter)
                .build();
    }


    @Bean
    public ItemProcessor processor(){
        return o -> {
            log.info("processing,do something:{}",o);
            return o;
        };
    }

}
